import 'dart:collection';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_list_page_widget/common_list_page_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_single_choice_button_widget/common_single_choice_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/bean/department_or_class_list_response.dart';
import 'package:e_reception_flutter/ui/company/company_detail/class_or_department/class_or_department_page.dart';
import 'package:e_reception_flutter/ui/create_user/user_course_class/course_class_bean/class_course_bean.dart';
import 'package:e_reception_flutter/ui/create_user/user_selectsort/bean/user_select_sort_save_response_bean.dart';

// import 'package:e_reception_flutter/ui/create_user/user_course_class/course_class_bean/course_class_bean.dart' hide ClassListResponse;
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/rich_text_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_http_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';


class MultiSelectClassCourseWidget extends StatefulWidget {
  final List<String> selectClassIds;

  MultiSelectClassCourseWidget(this.selectClassIds);

  @override
  _MultiSelectClassCourseWidgetState createState() =>
      _MultiSelectClassCourseWidgetState();

  ///跳转方法
  static Future<EditTextAndValue> navigatorPush(BuildContext context,
      List<String> selectClassIds) {
    return RouterUtils.routeForFutureResult<EditTextAndValue>(
      context,
      MultiSelectClassCourseWidget(selectClassIds),
    );
  }
}

class _MultiSelectClassCourseWidgetState
    extends State<MultiSelectClassCourseWidget> {
  List<DepartmentOrClassListItemBean> mList;
  final String _classType = "03";
  CommonListPageWidgetState mState;
  List<String> selectClassIds;
  List<String> cacheLastClass = new List(); //上次选中的班级id
  String keyword;

  String cacheKey;


  @override
  void initState() {
    selectClassIds=widget.selectClassIds??[];
    cacheKey=KEY_SELECT_CLASS +
        UserRepository.getInstance().getCacheKeySuffix();
    SharePreferenceUtil.getStringList(cacheKey
    ).then((value) {
      if(value!=null){
        cacheLastClass =value;
        setState(() {
        });
      }
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return CustomAnnotatedRegion(
       Scaffold(
        backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        body: CommonPackUpKeyboardWidget(
          child: Column(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              // color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
              _toTopBarWidget(),
              Container(
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                padding: const EdgeInsets.only(left: 7, right: 7, top: 10,bottom: 10),
                child: _searchDepartmentWidget(),
              ),

              //课程list
              _courseClassListWidget(),
            ],
          ),
        ),
      ),
      navigationBarColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
    );
  }

  Widget _courseClassListWidget() {
    return Expanded(
      child: CommonListPageWidget<DepartmentOrClassListItemBean, DepartmentOrClassListResponse>(
        enablePullUp: false,
        enablePullDown: true,
        queryMapFunc: (int page) =>
        {
          'authId': UserRepository.getInstance().authId,
          "current": 1,
          "size": '100',
          "type": '01',
          "searchName": keyword ?? ''
        },
        parseDataFunc: (VgHttpResponse resp) {
          DepartmentOrClassListResponse response = DepartmentOrClassListResponse.fromMap(resp?.data, ClassOrDepartmentPage.TYPE_CLASS);
          response?.data?.page?.records?.removeWhere((element) =>
          element == null ||
              StringUtils.isEmpty(element.classid) ||
              StringUtils.isEmpty(element.classname));
          if (response != null &&
              response.success &&
              response.data != null &&
              response.data.page != null &&
              response.data.page.records != null) {
            if (cacheLastClass != null && cacheLastClass.length > 0) {
              List<DepartmentOrClassListItemBean> newList = List();
              response.data.page.records.forEach((element) {
                if (cacheLastClass.contains(element.classid)) {
                  newList.insert(0, element);
                } else {
                  newList.add(element);
                }
              });
              response.data.page.records = newList;
            }
          }
          return response;
        },
        listFunc: (List<DepartmentOrClassListItemBean> courseList) {
          mList = courseList;
          mList.forEach((element) {
            element.isSelect = false;
          });
        },
        stateFunc: (CommonListPageWidgetState state) {
          mState = state;
        },
        itemBuilder: (BuildContext context, int index,
            DepartmentOrClassListItemBean itemBean) {
          if (itemBean == null) return Container();


          return _toListItemWidget(context, index, itemBean);
        },
        needCache: StringUtils.isEmpty(keyword),
        cacheKey:NetApi.DEPARTMENT_OR_CLASS_LIST+UserRepository.getInstance().getCacheKeySuffix(),
        //分割器构造器
        separatorBuilder: (context, int index, _) {
          return Container(
            height: 0,
            color: ThemeRepository.getInstance().getCardBgColor_21263C(),
            padding: const EdgeInsets.only(left: 15),
            child: Container(
              color: Color(0xFF303546),
            ),
          );
          // return divider;
        },
        placeHolderFunc: (List<DepartmentOrClassListItemBean> list, Widget child,
            VoidCallback onRefresh) {
          return VgPlaceHolderStatusWidget(
            emptyStatus: list == null || list.isEmpty,
            emptyOnClick: () => onRefresh(),
            child: child,
          );
        },
        netUrl:NetApi.DEPARTMENT_OR_CLASS_LIST,
        httpType: VgHttpType.post,
      ),
    );
  }


  Widget _toListItemWidget(
      BuildContext context, int index, DepartmentOrClassListItemBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        //判断字体是否选中
        // departmentText =
        if (selectClassIds.contains(itemBean.classid)) {
          selectClassIds.remove(itemBean.classid);
        } else {
          selectClassIds.add(itemBean.classid);
        }
        setState(() {});
      },
      child: Container(
        color: Color(0xFF21263C),
        height: 60,
        alignment: Alignment.centerLeft,
        padding: const EdgeInsets.symmetric(horizontal: 15,vertical: 10),
        child: Row(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(right: 10),
              child: CommonSingleChoiceButtonWidget(
                  (selectClassIds.contains(itemBean.classid))
                      ? CommonSingleChoiceStatus.selected
                      : CommonSingleChoiceStatus.unSelect),
            ),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Text(
              VgStringUtils.subStringAndAppendSymbol(itemBean?.classname , 20 ,symbol: "...")??"",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          color:  Color(0xFFD0E0F7),
                          // color: (selectClassIds.contains(itemBean.classid))
                          //     ? Color(0xFF1890FF)
                          //     : Color(0xFFD0E0F7),
                          fontSize: 15,
                        ),
                      ),
                      Spacer(),
                      Visibility(
                        visible: itemBean.adminCnt > 0,
                        child: Padding(
                          padding: const EdgeInsets.only(top: 1),
                          child: Text(
                              '管理员：${itemBean.adminCnt == 0 ? '' : (itemBean.adminCnt > 1 ? '${itemBean.adminName.substring(0, itemBean.adminName.indexOf(',')) ?? ''}等${itemBean.adminCnt}人' : itemBean.adminName ?? '0')}',
                              style: TextStyle(
                                fontSize: 10,
                                color: Color(0xff5e687c),
                              )),
                        ),
                      )
                    ],
                  ),
                  Spacer(),
                  RichTextWidget(
                    fontSize: 12,
                    contentMap: LinkedHashMap.from({
                      '学员':
                      Color(0xff5e687c),
                      '${itemBean.memberCnt}':
                      (itemBean?.memberCnt ?? 0) > 0
                          ? ThemeRepository.getInstance()
                          .getPrimaryColor_1890FF()
                          : Color(0xff5e687c),
                      '人': Color(0xff5e687c)
                    }),
                  )

                ],
              ),
            )
          ],
        ),
      ),
    );
  }


  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      title: "班级",
      rightWidget: _buttonWidget(),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: true,
        width: 48,
        height: 24,
        unSelectBgColor:
        ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 12,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color: Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          SharePreferenceUtil.putStringList(cacheKey, selectClassIds);
          Navigator.pop(context, EditTextAndValue(editText:mList.where((element) {
            return selectClassIds.contains(element.classid);
          }).toList().map((e) => e.classname).join('、'),value: selectClassIds));
        },
      ),
    );
  }

  Widget _searchDepartmentWidget() {
    return Container(
      height: 30,
      child: CommonEditCallbackWidget(
        backGroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
        contentPadding: EdgeInsets.only(top: 0, bottom: 15),
        hintText: "搜索",
        customIcon: "images/common_search_ico.png",
        iconColor: Colors.white54,
        onChanged: (String keyword) {
          //搜索
          this.keyword=keyword;
          mState.viewModel.refresh();
        },
        onSubmitted: (keyword){
          this.keyword=keyword;
          mState.viewModel.refresh();
        },
      ),
    );
  }
}
